<template>
	<view class="">
		<map style="width: 750rpx;height: 100vh; z-index: 9;" id="navi_map" :show-location="false"
			:enable-traffic="true" :longitude="markers[0].longitude" :latitude="markers[0].latitude" scale="18"
			:markers="markers" :include-points="includePoints" :polyline="polyline" @tap="addPostion">
		</map>
		<view class="centent-box">
			<view class="hint">
				路长：{{distance}}
			</view>
			<view class="hint">
				预计时长：{{duration}}
			</view>
		</view>
	</view>
</template>

<script>
	import amap from "@/config/amap-wx.130.js"
	export default {
		data() {
			return {
				// 彩虹线颜色
				colorList: ["#00FF00", "#FFFF00", "#FF0000", "#FF00FF", "#00FFFF", "#33FF66", "#CC3366", "#FFCCFF",
					"#0091ff"
				],
				// 高德地图key
				key: 'd89f7acd7154fd23ab978f73cffa4d10',
				// markers:[] 这个数组一定要有两个 代表起点和终点的样式和位置
				markers: [{
						iconPath: "https://yuyitang.oss-cn-shenzhen.aliyuncs.com/hop/image/%E5%A4%96%E5%8D%96.png", // 起点
						id: 0,
						latitude: '',
						longitude: '',
						width: 48,
						height: 48,
					},
					{
						iconPath: "https://yuyitang.oss-cn-shenzhen.aliyuncs.com/hop/image/%E6%94%B6%E8%B4%A7%E5%9C%B0%E5%9D%80.png", // 终点
						id: 1,
						latitude: '23.03523496103158',
						longitude: '113.29348477577209',
						width: 48,
						height: 48,
					},

				],
				myAmapFun: '',
				locations: {}, //这个是从其他页面获取的起点终点经纬度对象
				polyline: [], // 渲染路线
				distance: 0, // 路长
				duration: 0, //路时
				includePoints: [], // 视眼包括起始点和终点
				index: 1, 
			}
		},
		onLoad() {
			// 第一次绘制起点和终点路线
			this.drayMap(uni.getStorageSync('location').split(',')[0], uni.getStorageSync('location').split(',')[1])
			// 地图能够显示起点和终点
			this.showCourier(uni.getStorageSync('location').split(',')[0], uni.getStorageSync('location').split(',')[1])
			// 获取授权情况			
			this.toSetting()
			
			/** 配送员平滑移动 */
			// const that = this
			// setInterval(() => {
			// 	that.courierXy()
			// }, 10000)
		},
		methods: {
			// 显示两点
			showCourier(latitude, longitude) {
				let mapCtx = wx.createMapContext('navi_map', this)
				mapCtx.includePoints({
					padding: [70, ],
					points: [{
							longitude: longitude,
							latitude: latitude
						},
						{
							longitude: '113.29348477577209',
							latitude: '23.03523496103158'
						}
					]
				})
			},
			// 初始化高德地图
			drayMap(latitude, longitude) {
				// 路线规划
				const that = this
				var myAmapFun = new amap.AMapWX({
					key: this.key,
				});
				this.polyline = []
				this.markers[0].latitude = latitude
				this.markers[0].longitude = longitude
				let postionData = longitude + ',' + latitude
				myAmapFun.getRidingRoute({
					origin: postionData,
					destination: '113.29348477577209,23.03523496103158',
					success: function(data) {
						// console.log(data);
						// 途经点
						let points = [];
						// 彩虹线
						let colorWire = [];
						let steps = data.paths[0].rides;
						for (let i = 0; i < steps.length; i++) {
							let poLen = steps[i].polyline.split(';');
							let ids = 0;
							for (let j = 0; j < poLen.length; j++) {
								if (j % 17 == 0) {
									ids = Math.round(Math.random() * (that.colorList.length - 1))
								}
								colorWire.push(that.colorList[ids])
								points.push({
									longitude: parseFloat(poLen[j].split(',')[0]),
									latitude: parseFloat(poLen[j].split(',')[1])
								})
							}
						}
						that.polyline.push({
							points: points,
							// color: "#0091ff",
							arrowLine: true,
							level: true,
							colorList: colorWire,
							width: 10
						})

						if (data.paths[0] && data.paths[0].distance) {
							let Km = Math.floor(data.paths[0].distance / 1000).toFixed(0) > 0 ? Math.floor(data
								.paths[0].distance / 1000).toFixed(0) + '公里' : ''
							let rice = Math.floor(data.paths[0].distance % 1000).toFixed(0) > 0 ? (Math.floor(
								data.paths[0].distance % 1000).toFixed(0) > 9 ? Math.floor(data.paths[
								0].distance % 1000).toFixed(0) : '0' + Math.floor(data.paths[0]
								.distance % 1000).toFixed(0)) + '米' : ''
							let hours = Math.floor(data.paths[0].duration / 3600).toFixed(0) > 0 ? Math.floor(
								data.paths[0].duration / 3600).toFixed(0) + '小时' : ''
							let minute = (Math.floor(data.paths[0].duration % 3600 / 60).toFixed(0) == 0?1:Math.floor(data.paths[0].duration % 3600 / 60).toFixed(0)) + '分钟'
							that.distance = Km + rice
							that.duration = hours + minute
						}
					},
					fail: function(info) {
						console.log(info);
					}
				})
			},



			// 动态设置骑手经纬度
			addPostion(e) {
				console.log(e);
				this.drayMap(e.detail.latitude, e.detail.longitude)
				
			},
			
			
			// 配送员平移
			courierXy(){
				const that = this
				var mapContext = uni.createMapContext('navi_map', this)
				let index = this.index; 
				let translateMarkerConfig = {
					markerId: 0,
					destination: {
						longitude: that.polyline[0].points[index].longitude, // 车辆即将移动到的下一个点的经度  
						latitude: that.polyline[0].points[index].latitude, // 车辆即将移动到的下一个点的纬度  
					},
					duration: 2000, // 持续时间
					autoRotate: false, // 自动旋转
					success: (e) => {
						console.log(e)
					},
					fail: (err) => {
						console.log(err)
					}
				};
				this.index +=1;  
				console.log(translateMarkerConfig)  
				mapContext.translateMarker(translateMarkerConfig); 
			},
			

			// 获取实时定位
			getNewPotion() {
				const that = this
				const _locationChangeFn = function(res) {
					console.log(new Date().getHours() + ':' + new Date().getMinutes() + ':' + new Date().getSeconds())
					console.log(res)
					that.markers[0].latitude = ''
					that.markers[0].longitude = ''
					// that.markers[0].latitude = res.latitude
					// that.markers[0].longitude = res.longitude
					that.drayMap(res.latitude, res.longitude)
					wx.offLocationChange(_locationChangeFn)
				}
				setInterval(function(date) {					
					wx.startLocationUpdateBackground({
						success(res) {
							wx.onLocationChange(_locationChangeFn)

						},
						fail(res) {
							// console.log('开启后台定位失败', res)
							wx.openSetting({
								success: ops => {
									console.log(ops);
								}
							})
						}
					})
				}, 10000)
			},

			// 设置权限
			toSetting() {
				const that = this
				uni.getSetting({
					success(res) {
						if (!res.authSetting['scope.userLocationBackground']) {
							// 小程序定位实时授权
							wx.startLocationUpdateBackground({
								type: 'gcj02',
								success: (res) => {
									console.log(res);
								},
								fail: (err) => {
									console.log(err);
									uni.showModal({
										title: '',
										content: '请在系统设置中打开定位服务,开启后需要授权才能查看即时配送功能',
										confirmText: '确定',
										success: function(res) {
											uni.openSetting({
												success(auth) {
													if (auth.authSetting[
															'scope.userLocationBackground'
															]) {
														// 小程序定位实时授权
														wx.startLocationUpdateBackground({
															type: 'gcj02',
															success: (
																res) => {
																	console
																		.log(
																			res
																			);
																	that.getNewPotion()
																},
															fail: (
															err) => {
																console
																	.log(
																		err
																		);
															}
														})
													} else {
														// 没有允许定位权限
														uni.showToast({
															title: '您拒绝了定位权限，将无法使用地图功能',
															icon: 'none'
														});
													}
												}
											})
										}
									})
								}
							})
						} else {
							// 小程序定位实时授权
							wx.startLocationUpdateBackground({
								type: 'gcj02',
								success: (res) => {
									console.log(res);
									that.getNewPotion()
								},
								fail: (err) => {
									console.log(err);
								}
							})
						}
					}
				})
			},

		}
	}
</script>

<style>
	.centent-box {
		height: 120rpx;
		position: fixed;
		bottom: 60rpx;
		left: 30rpx;
		right: 30rpx;
		background: #FFFFFF;
		border-radius: 20rpx;
		z-index: 99;
	}

	.hint {
		font-size: 32rpx;
		font-weight: 500;
		color: black;
		margin-top: 10rpx;
		margin-left: 30rpx;
	}
</style>
